package com.tsh.chat.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.tsh.chat.domain.ChatHistory;
import com.tsh.chat.domain.MessageBody;
import com.tsh.chat.service.ChatService;
import com.tsh.common.security.utils.SecurityUtils;
import com.tsh.chat.util.ChatUtil;
import com.tsh.common.core.web.controller.BaseController;
import com.tsh.common.core.web.domain.AjaxResult;
import com.zhipu.oapi.service.v4.model.ChatMessage;
import com.zhipu.oapi.service.v4.model.ChatMessageRole;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/chat")
public class ChatController extends BaseController {

    @Autowired
    private ChatService chatService;

    /**
     * 单次对话
     * @return 返回对话回复
     */
    @PostMapping("/send")
    public AjaxResult sendMessage(@RequestBody MessageBody messageBody) {
        String response = null;
        try {
            response = ChatUtil.testFunctionSSE(messageBody.getMessage());
        }catch (JsonProcessingException e){
            logger.info("API响应出现了一点问题...");
            e.printStackTrace();
        }
        return success(response);
    }

    /**
     * 获取对话记录，连续对话用
     * @return 返回所有对话记录
     */
    @GetMapping("/chatHistory")
    public AjaxResult chatHistory(@RequestParam int userId) {
        List<ChatHistory> chatHistoryList = chatService.getChatHistoryByUserId(userId);
        if (chatHistoryList != null && !chatHistoryList.isEmpty()) {
            return AjaxResult.success("查询成功", chatHistoryList);
        } else {
            return AjaxResult.success("当前聊天记录为空");
        }
    }

    /**
     * 删除历史对话
     * @return
     */
    @DeleteMapping("/{userId}")
    public AjaxResult delChatHistory(@PathVariable int userId)
    {
        if (userId != SecurityUtils.getUserId())
        {
            return error("当前用户不能删除");
        }
        return toAjax(chatService.deleteHistoryById(userId));
    }

    /**
     * 连续对话
     * @return
     */
    @PostMapping("/memory")
    public AjaxResult chatMemory(@RequestBody MessageBody messageBody) {
        if(messageBody.getUuid() != SecurityUtils.getUserId()){
            return error("无权操作!请求ID:" + messageBody.getUuid() + "当前用户ID:" + SecurityUtils.getUserId());
        }
        if(messageBody.getMessage().isEmpty()) return error("内容不能为空!");
        List<ChatMessage> messages = new ArrayList<>();
        List<ChatHistory> chatHistoryList = chatService.getChatHistoryByUserId(messageBody.getUuid());
        for (ChatHistory content: chatHistoryList){
            ChatMessage chatMessage = new ChatMessage(content.getRole(), content.getContent());
            messages.add(chatMessage);
        }
        ChatMessage newChatMessage = new ChatMessage(ChatMessageRole.USER.value(), messageBody.getMessage());
        messages.add(newChatMessage);
        try{
            String newAnswer = ChatUtil.constantChatSSE(messages);
            /**
             * 获取最新回复成功，新增的对话保存到数据库
             */
            chatService.insertNewChat(messageBody.getUuid(), ChatMessageRole.USER.value(), messageBody.getMessage());
            chatService.insertNewChat(messageBody.getUuid(), ChatMessageRole.ASSISTANT.value(), newAnswer);
        }catch (JsonProcessingException e){
            e.printStackTrace();
            logger.info("连续对话模块出现了意外...");
            return error("连续对话出现了一点意外...");
        }
        return success();
    }
}
